summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/uic/barcode/utils/SecurityUtils.java
blob: 8f19e4b26289b2ba5868af0ab513c0084f6cdbe4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package org.uic.barcode.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.Provider.Service;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;

import org.uic.barcode.dynamicFrame.Constants;

/**
 * The Class SecurityUtils.
 */
public class SecurityUtils {
	
	/**
	 * Find provider by public key.
	 *
	 * @param keyAlgorithmOid the key algorithm oid
	 * @param keyBytes the encoded bytes of the public key
	 * @return the provider
	 */
	public static Provider findPublicKeyProvider(String keyAlgorithmOid, byte[] keyBytes) {
				
 		Provider[] provs = Security.getProviders();
 		for (Provider provider : provs) {
 			try {
 				PublicKey key = ECKeyEncoder.fromEncoded(keyBytes, keyAlgorithmOid, provider);
 				if (key != null) return provider;
			} catch (Exception e1) {
				//try next
			} 
 		}
 		return null;
	}

	/**
	 * Find private key provider.
	 *
	 * @param key the private key
	 * @return the provider
	 */
	public static Provider findPrivateKeyProvider(PrivateKey key) {
		
		String name = key.getAlgorithm();
		byte[] keyBytes = key.getEncoded();
		
		if (keyBytes == null || keyBytes.length == 0) {
			return null;
		}
			
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		
	
		KeyFactory keyFactory = null;
		
 		Provider[] provs = Security.getProviders();
 		for (Provider provider : provs) {
 			try {
 				keyFactory = KeyFactory.getInstance(name,provider);
			} catch (NoSuchAlgorithmException e1) {
				//try next
			} 
 		    if (keyFactory != null) {
 		    	try {
 		    		keyFactory.generatePrivate(keySpec);
 		    		return provider;
 		    	} catch (Exception e) {
 		    		provider = null;
 		    		//try next
 		    	}
 		    }
 		}
 		
 		return null;
	}
	
	
	
	/**
	 * Convert.
	 *
	 * @param key the key
	 * @param provider the provider
	 * @return the public key
	 */
	public static PublicKey convert(PublicKey key, Provider provider) {
		
		PublicKey publicKey;
		KeyFactory keyFactory = null;
		
		try {
			if (key.getAlgorithm() != null && key.getAlgorithm().toUpperCase().contains("EC") ) {
				keyFactory = KeyFactory.getInstance("EC",provider);
			} else if (key.getAlgorithm() != null && key.getAlgorithm().length() > 0 ) {
				keyFactory = KeyFactory.getInstance("DSA",provider);
			} else {
				return key;
			}
			publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(key.getEncoded()));
		} catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
			return key;
		}
		
		return publicKey;
		
		
	}
	
	
	/**
	 * Convert.
	 *
	 * @param key the key
	 * @param provider the provider
	 * @return the private key
	 */
	public static PrivateKey convert(PrivateKey key, Provider provider) {
		
		PrivateKey privateKey;
		KeyFactory keyFactory = null;
		
		try {
			if (key.getAlgorithm() != null && key.getAlgorithm().toUpperCase().contains("EC") ) {
				keyFactory = KeyFactory.getInstance("EC",provider);
			} else if (key.getAlgorithm() != null && key.getAlgorithm().length() > 0 ) {
				keyFactory = KeyFactory.getInstance("DSA",provider);
			} else {
				return key;
			}
			privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(key.getEncoded()));
		} catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
			return key;
		}
		
		return privateKey;
		
		
	}

	/**
	 * Find signature provider.
	 *
	 * @param encoded the encoded
	 * @param oid the oid
	 * @return the provider
	 */
	public static Provider findSignatureProvider(byte[] encoded, String oid) {
		
		KeyFactory keyFactory = null;
		String signatureAlgorithmName = null;
		
		Provider[] provs = Security.getProviders();
 		for (Provider provider : provs) {
 			try {
 				Service service = provider.getService(AlgorithmNameResolver.TYPE_SIGNATURE_ALG, oid);
 				if (service != null) {
 					signatureAlgorithmName = service.getAlgorithm();
 					if (signatureAlgorithmName != null && signatureAlgorithmName.length() > 0) {
 						if (signatureAlgorithmName.toUpperCase().contains("EC") ) {
 							keyFactory = KeyFactory.getInstance("EC",provider);
 						} else {
 							keyFactory = KeyFactory.getInstance("DSA",provider);
 						}
 						if (keyFactory != null) {
 							X509EncodedKeySpec spec = new X509EncodedKeySpec(encoded);
 							//try to encode the key
 							keyFactory.generatePublic(spec);						
 						}
 					}
 				}
			} catch (Exception e1) {
				keyFactory = null;
			} 
 		    if (keyFactory != null) {
 		    	return keyFactory.getProvider();
 		    }
 		}
		
		return null;
	}
	
	/**
	 * Decode signature integer sequence.
	 * 
	 * Support function to decode a DSA signature
	 * Provides the two DSA signature parameter encoded in a DSA signature
	 *
	 * @param bytes the bytes
	 * @return the big integer[]
	 * @throws Exception the exception
	 */
	public static BigInteger[] decodeSignatureIntegerSequence(byte[] bytes) throws Exception {

		int sequenceTag = (int) bytes[0];
		
		if (sequenceTag != 48) throw new Exception("signature is not a sequence");
		
		int sequenceLength = (int) bytes[1];
		
		if (sequenceLength < 6) throw new Exception("signature sequence too short");
		
		BigInteger[] result = new BigInteger[2];
		
		int offset = 2;
		int i = 0;
		while (offset < bytes.length && i < 2) {
			int integerTag = (int) bytes[offset];
			if (integerTag != 2) throw new Exception("signature is not an integer sequence");
			int integerLength = (int) bytes[offset + 1];
			byte[] value = Arrays.copyOfRange(bytes, offset + 2, offset + 2 + integerLength);		
			result[i] = new BigInteger(+1, value);
			offset = offset + integerLength + 2;
			i++;
		}

		return result;
	}
	
	/**
	 * Encode signature integer sequence.
	 *  
	 *  Support function to format two parameters as DER encoded integer list 
	 *  to get a valid formated DSA signature from the signature parameter
	 *
	 * @param i1 the i 1
	 * @param i2 the i 2
	 * @return the byte[]
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public static byte[] encodeSignatureIntegerSequence(BigInteger i1, BigInteger i2) throws IOException {
		
		//SEQUENCE OF --> tag 16
		int sequenceTag = 16 + 32;  // (bits 6 = 1 constructed)
		//INTEGER     --> tag 2
		int integerTag = 2;
			
		byte[] b1 = i1.toByteArray();
        int lb1 = b1.length;
		byte[] b2 = i2.toByteArray();
        int lb2 = b2.length;		
        
        int sequenceLength = lb1 + lb2 + 4;
		
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		
		out.write((byte) sequenceTag);
		out.write((byte) sequenceLength);   
		out.write((byte) integerTag);  
		out.write((byte) lb1);  
		out.write(b1);   
		out.write((byte) integerTag);  
		out.write((byte) lb2);  
		out.write(b2);   

		return out.toByteArray();
	}

	/**
	 * Recombine dsa signature.
	 *
	 * @param sealdata the sealdata
	 * @return the byte[]
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public static byte[] recombineDsaSignature(byte[] sealdata) throws IOException {
		
		//check whether the encoding is wrong and the sealdata contain a signature
		//remove trailing zeroes from the signature
		BigInteger[] bInts = null;
		try {
			bInts = decodeSignatureIntegerSequence(sealdata);
			byte[] sig = encodeSignatureIntegerSequence(bInts[0],bInts[1]);
			//decoding the entire signature was ok, so there was no split
			return sig;
		} catch (Exception e) {
			//the signature is correctly implemented, continue with recombination
		}

		// split the data into two blocks
		int length = sealdata.length / 2;
		byte[] rBytes = Arrays.copyOfRange(sealdata,      0, length);
		byte[] sBytes = Arrays.copyOfRange(sealdata, length, length + length);	
		
		//convert to BigInteger to get rid of leading zeroes
		BigInteger r = new BigInteger(1,rBytes);
		BigInteger s = new BigInteger(1,sBytes);	
		
		//encode as DSA signature structure
		//SEQUENCE OF --> tag 16
		int sequenceTag = 16 + 32;  // (bits 6 = 1 constructed)
		//INTEGER     --> tag 2
		int integerTag = 2;
		
		byte[] b1 = r.toByteArray();
        int lb1 = b1.length;     

        byte[] b2 = s.toByteArray();	
        int lb2 = b2.length;		
        int sequenceLength = lb1 + lb2 + 4;
		
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		out.write((byte) sequenceTag);
		out.write((byte) sequenceLength);   
		out.write((byte) integerTag);  
		out.write((byte) lb1);  
		out.write(b1);   
		out.write((byte) integerTag);  
		out.write((byte) lb2);  
		out.write(b2);   
		return out.toByteArray();		

	}
	
	/**
	 * Gets the dsa algorithm allowed for ssb or static frame.
	 *
	 * @param bs the size of the signature
	 * @return the dsa algorithm OID
	 */
	public static String getDsaAlgorithm(byte[] bs) {
		
		 BigInteger[] bInts = null;
		 int size = 0;
		 try {
			bInts = decodeSignatureIntegerSequence(bs);
			int sizeR = bInts[0].bitLength();
			int sizeS = bInts[1].bitLength();
			size = Math.max(sizeR,sizeS);
		 } catch (Exception e) {
			return null;
		 }
		
		 if (size > 224) {
		   return Constants.DSA_SHA256;
		 } else if (size > 160) {
		   return Constants.DSA_SHA224;
		 } else {
		   return Constants.DSA_SHA1;
		 }
	}
}